const uniID = require('uni-id-common');  // 引入 uniID
const db = uniCloud.database();          // 数据库实例

exports.main = async (event, context) => {
  const uniIDIns = uniID.createInstance({ context });

  let body = event;
  if (event.body != undefined) {
    body = JSON.parse(event.body);
  }

  try {
    // 1. 验证用户身份
    const { uid } = await uniIDIns.checkToken(body.uniIdToken);
    if (!uid) {
      return { code: 403, msg: '身份验证失败' };
    }

    // 2. 提取需要更新的字段
	const { name, expertise, avatar } = body;
	let experience = Number(body.experience); // 强制转为数字
	
	if(isNaN(experience)){
		 return { code: 400, msg: 'experience值无效' };
	}
	
	if (!name || !expertise || isNaN(experience)) {
	  return { code: 400, msg: '缺少必填字段' };
	}

    // 3. 查找咨询师记录
    const consultantRes = await db.collection('consultants')
      .where({ user_id: uid })
      .get();

    if (!consultantRes.data || consultantRes.data.length === 0) {
      return { code: 404, msg: '未找到该用户的咨询师信息' };
    }

    const consultantId = consultantRes.data[0]._id;

    // 4. 更新数据
    const updateRes = await db.collection('consultants')
      .doc(consultantId)
      .update({
        name,
        expertise,
        avatar,
        experience,
        update_date: new Date().toISOString()
      });

    return {
      code: 0,
      msg: '咨询师信息更新成功',
      updateRes
    };

  } catch (e) {
    console.error('更新咨询师信息出错:', e);
    return { code: 500, msg: '服务器内部错误', detail: e };
  }
};
